package com.ebelter.btlibrary.btble.ble.bluetooth.device.impl;

import com.ebelter.btlibrary.btble.ble.bluetooth.device.InternalChannel;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 蓝牙返回信息解析者，用于蓝牙数据协议，解析蓝牙数据
 * 1.解密
 * 2.解析
 * 3.区分业务
 * 4.回调接口，返回结果
 * Created by Sergio Pan on 2017/11/28.
 */

public abstract class BleMessageAnalyser {

    private StringBuffer sb;

    protected InternalChannel mInternalChannel;
    //数据解析后的各种回调
    protected byte dataHeaderReceive;

    public void setDataHeaderReceive(byte dataHeaderReceive) {
        this.dataHeaderReceive = dataHeaderReceive;
    }

    public void registerInternalChannel(InternalChannel channel) {
        this.mInternalChannel = channel;
    }

    /**
     * 接收数据
     *
     * @param channel
     * @param data
     */
    public void onReceiveBleMessage(Channel channel, byte[] data) {
        analyze(channel, decrypt(data));
    }

    /**
     * 解密
     *
     * @param data
     * @return
     */
    protected byte[] decrypt(byte[] data) {
        return data;
    }

    /**
     * 解析数据
     *
     * @param channel
     * @param data
     */
    protected abstract void analyze(Channel channel, byte[] data);


    /**
     * 高8位低8位拼接
     *
     * @param high 高8位字节
     * @param low  低8位字节
     * @return
     */
    protected int get2ByteValue(byte high, byte low) {
        return ((high & 0xff) << 8) | (low & 0xff);
    }


    protected synchronized String getArrayString(byte[] data) {
        if (sb == null) {
            sb = new StringBuffer();
        }
        sb.setLength(0);
        int i = 0;
        while (i < data.length) {
            sb.append(Integer.toHexString(data[i] & 0xff)).append(" ");
            i++;
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    protected void sendToCommndEditor() {

    }

    private SimpleDateFormat sdf;

    protected String getMeasureTimeStr(long measureTime) {
        if (sdf == null) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        Date curDate = new Date(measureTime);
        return sdf.format(curDate);
    }


    public void onRelease() {
        mInternalChannel = null;
    }

}
